//
//  ContactViewController.m
//  QRCodeManager
//
//  Created by Cosmin Stirbu on 4/17/13.
//  Copyright (c) 2013 Cosmin Stirbu. All rights reserved.
//

#import "ContactViewController.h"
#import "WebViewController.h"
#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>

@interface ContactViewController ()

@end

@implementation ContactViewController

@synthesize qrContact;


- (void)viewDidLoad
{
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)viewWillAppear:(BOOL)animated {
    // Set Up The UI
    _nameLabel.text = qrContact.contactName;
    _companyLabel.text = qrContact.company;
    _phoneLabel.text = qrContact.phone;
    _emailLabel.text = qrContact.email;
    _addressLabel.text = qrContact.address;
    _websiteLabel.text = qrContact.website;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    switch (indexPath.row) {
        case 2: {
            // Call store
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:[NSString stringWithFormat:NSLocalizedString(@"call_alert_message", nil), qrContact.phone] delegate:self
                                                  cancelButtonTitle:NSLocalizedString(@"alert_cancel", nil) otherButtonTitles:NSLocalizedString(@"alert_ok", nil), nil];
            [alert show];
            break;
        }
        case 3: {
            // Email
            if ([MFMailComposeViewController canSendMail])
            {
                MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];
                mailer.mailComposeDelegate = self;
                NSArray *toRecipients = [NSArray arrayWithObjects:qrContact.email, nil];
                [mailer setToRecipients:toRecipients];
                [self presentModalViewController:mailer animated:YES];
            }
            break;
        }
        case 5: {
            if (qrContact.website != nil || ![qrContact.website isEqualToString:@""]) {
                [self performSegueWithIdentifier:@"Contact_WebView" sender:self];
            }
            break;
        }
    }
    if (indexPath.section == 1) {
        // Add Contact
        [self addContact];
    }
}


- (void)callContact {
	NSString *callString=[[NSString alloc] initWithFormat:@"tel:%@", qrContact.phone];
	UIApplication * app = [UIApplication sharedApplication];
	[app openURL: [NSURL URLWithString:callString]];
}

- (void)addContact {
    // create person record
    ABRecordRef person = ABPersonCreate();
    
    // set name and other string values
    
    ABRecordSetValue(person, kABPersonOrganizationProperty, (__bridge CFStringRef) qrContact.contactName, NULL);
    
    if (qrContact.website)
    {
        ABMutableMultiValueRef urlMultiValue = ABMultiValueCreateMutable(kABMultiStringPropertyType);
        ABMultiValueAddValueAndLabel(urlMultiValue, (__bridge CFStringRef) qrContact.website, kABPersonHomePageLabel, NULL);
        ABRecordSetValue(person, kABPersonURLProperty, urlMultiValue, nil);
        CFRelease(urlMultiValue);
    }
    
    if (qrContact.email)
    {
        ABMutableMultiValueRef emailMultiValue = ABMultiValueCreateMutable(kABMultiStringPropertyType);
        ABMultiValueAddValueAndLabel(emailMultiValue, (__bridge CFStringRef) qrContact.email, kABWorkLabel, NULL);
        ABRecordSetValue(person, kABPersonEmailProperty, emailMultiValue, nil);
        CFRelease(emailMultiValue);
    }
    
    if (qrContact.phone)
    {
        ABMutableMultiValueRef phoneNumberMultiValue = ABMultiValueCreateMutable(kABMultiStringPropertyType);
        NSArray *venuePhoneNumbers = [qrContact.phone componentsSeparatedByString:@" or "];
        for (NSString *venuePhoneNumberString in venuePhoneNumbers)
            ABMultiValueAddValueAndLabel(phoneNumberMultiValue, (__bridge CFStringRef) venuePhoneNumberString, kABPersonPhoneMainLabel, NULL);
        ABRecordSetValue(person, kABPersonPhoneProperty, phoneNumberMultiValue, nil);
        CFRelease(phoneNumberMultiValue);
    }
    
    // add address
    
    ABMutableMultiValueRef multiAddress = ABMultiValueCreateMutable(kABMultiDictionaryPropertyType);
    NSMutableDictionary *addressDictionary = [[NSMutableDictionary alloc] init];
    
    if (qrContact.address)
    {
        addressDictionary[(NSString *) kABPersonAddressStreetKey] = qrContact.address;
    }
    
    ABMultiValueAddValueAndLabel(multiAddress, (__bridge CFDictionaryRef) addressDictionary, kABWorkLabel, NULL);
    ABRecordSetValue(person, kABPersonAddressProperty, multiAddress, NULL);
    CFRelease(multiAddress);
    
    // let's show view controller
    
    ABUnknownPersonViewController *controller = [[ABUnknownPersonViewController alloc] init];
    
    controller.displayedPerson = person;
    controller.allowsAddingToAddressBook = YES;
    
    // current view must have a navigation controller
    [self.navigationController pushViewController:controller animated:YES];
    
    CFRelease(person);
}

#pragma mark - AlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex != alertView.cancelButtonIndex) {
        [self callContact];
    }
}

#pragma mark - MFMailComposerDelegate Methods

- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{
    switch (result)
    {
        case MFMailComposeResultSent: {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:NSLocalizedString(@"mail_sent_message", nil) delegate:nil cancelButtonTitle:NSLocalizedString(@"message_ok", nil) otherButtonTitles: nil];
            [alert show];
            break;
        }
        case MFMailComposeResultFailed:
            NSLog(@"Mail failed: the email message was not saved or queued, possibly due to an error.");
            break;
        default:
            NSLog(@"Mail not sent.");
            break;
    }
    // Remove the mail view
    [self dismissModalViewControllerAnimated:YES];
}


#pragma mark - Segue 

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    WebViewController *webViewController =  (WebViewController *)[segue destinationViewController];
    webViewController.url = qrContact.website;
}

- (void)viewDidUnload {
    _nameLabel = nil;
    _companyLabel = nil;
    _emailLabel = nil;
    _addressLabel = nil;
    _websiteLabel = nil;
    _phoneLabel = nil;
    [super viewDidUnload];
}
@end
